<template>
  <div class="card-out-container">
    <a-spin :spinning="spinning">
      <a-row class="mb-15">
        <a-col :span="6">
          <a-button type="primary" @click="exportTable" class="mr-10">{{ $t('common.outputExcel') }}</a-button>
          <!-- <a-button type="primary" ghost @click="printTable">{{ $t('common.print') }}</a-button> -->
        </a-col>
        <a-col :span="18" class="full-width flex-right">
          <a-form layout="inline">
            <a-form-item :label="$t('other.selectTime')">
              <a-range-picker v-model:value="queryParam.time" :placeholder="[$t('common.startDate'), $t('common.endDate')]" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" @change="loadData" />
            </a-form-item>
            <a-form-item>
              <a-input-search v-model:value.trim="queryParam.staffNameOrstaffNo" enter-button :placeholder="$t('basicData.name')+'/'+$t('basicData.jobNo')" @search="loadData" style="width:225px;" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-table rowKey="id" :loading="loading" bordered size="small" :dataSource="dataSource" :columns="columns" :scroll="{y: 'calc(100vh - 390px)'}" :pagination="ipagination" @change="handleTableChange" :rowSelection="null" :operateMargin="true" :rowClassName="rowClassName">
        <template #bodyCell="{ column, record ,text}">
          <template v-if="column.key === 'styleName'">
            <span v-if="record.styleName && record.styleName.length<=10" :title="text">{{ record.styleName}}</span>
            <a-tooltip v-else>
              <template #title>
                <span>{{record.styleName}}</span>
              </template>
              <span :title="record.styleName">{{record.styleName && record.styleName.substr(0, 7) + '...'}}</span>
            </a-tooltip>
          </template>
        </template>
        <template #footer>
          <div class="text-right">
            {{$t('report.total')}}: {{tableTotal}}
          </div>
        </template>
      </a-table>

      <div style="display:none;">
        <a-table id="printId" :loading="loading" bordered size="small" :dataSource="printDataList" :columns="printColumnsArr" :pagination="false">

        </a-table>
      </div>
    </a-spin>
  </div>
</template>
<script>
import { ListMixinPm } from '@/mixin/listMixinPm.js'
import { columns } from './modules/config.js'
import { cloneDeep } from 'lodash'
import { endTimeValue, filterObj, startTimeValue } from '@/utils'
import { mapState } from 'vuex'
import { store } from '@/store'
import axios from "@/utils/request"
import printJS from "print-js"
export default {
  name: 'staffStyleIncome',
  mixins: [ListMixinPm],
  data () {
    return {
      columns,
      spinning: false,
      printDataList: [],
      ipagination: {
        current: 1,
        pageSize: 50,
        pageSizeOptions: ['50', '100', '200'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('common.total') + total + this.$t('common.piece')
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      url: {
        list: '/api/report/staff-style-output',
        exportUrl: '/api/report/export-staff-style-output'
      },
      columnsArr: [],
      columnsTitleArr: [],
      printColumnsArr: [],
      lotList: [], // 床号
      tableTotal: 0
    }
  },
  computed: {
    ...mapState({
      styleList: state => state.normalData.styleList,
      allMakeList: state => state.normalData.allMakeList
    })
  },
  methods: {
    rowClassName (record) {
      if (record.totalQuantity) return 'trBackgroundColor'
    },
    getQueryParams () {
      let param = cloneDeep(this.queryParam)
      if (this.queryParam.time && this.queryParam.time.length) {
        param.startProductTime = startTimeValue(this.queryParam.time[0])
        param.endProductTime = endTimeValue(this.queryParam.time[1])
      }
      delete param.time
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    loadData (arg) {
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) { this.ipagination.current = 1 }
      let params = this.getQueryParams()
      if (!params) return
      // 查询条件
      this.loading = true
      axios.postAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data ? res.data.staffStyleOutputList : []
          res.data && (this.ipagination.total = this.dataSource.length || 0)
          this.tableTotal = res.data.totalQuantity
        }
        this.loading = false
      }).finally(() => {
        this.loading = false
        this.tableKey = Math.random()
      })
    },
    async printTable () {
      await this.getColumnsList()
      this.queryParam.pageNo = 1
      this.queryParam.pageSize = 65335
      // console.log(this.queryParam)
      const res = await axios.postAction(this.url.list, this.queryParam);
      if (!res.data) return
      this.spinning = true;
      if (res) {
        this.printDataList = res.data.staffStyleOutputList
        if (this.printDataList.length > 0) {
          setTimeout(() => {
            this.printTableData();
            this.spinning = false;
          }, 2000);
        } else {
          this.spinning = false;
        }
      }
    },
    //打印  请求做好的导出接口 变更数据展示
    printTableData () {
      printJS({
        printable: "printId", // 标签元素id
        type: "html",
        documentTitle: "["+this.$t('other.staffIncome')+"]",
        style: "#printId{width:100%;} "
          + " #printId .ant-table-thead>tr>th, #printId .ant-table-tbody>tr>td  {border: 1px solid #bcb8b8;border-collapse: collapse;} "
          + " #printId table{border-collapse: collapse;} "
      });
    },
    async exportTable () {
      await this.getColumnsList()
      let query = this.getQueryParams()
      let param = {
        ...query,
        No: 1,
        pageSize: 65335,
        columns: this.columnsArr,
        tables: this.columnsTitleArr
      }
      this.exportExcels(this.url.exportUrl, this.$t('other.staffStyleOutputTable'), true, param)
    },
    async getColumnsList () {
      let colArr = [];
      let paramsArr = [];
      let titleArr = [];
      let hangerTrackTable = columns

      if (hangerTrackTable && hangerTrackTable.length > 0) {
        hangerTrackTable.forEach(
          item => {
            paramsArr.push(item.dataIndex)
            titleArr.push(item.title)
            colArr.push(item)
          }
        )
      }
      this.columnsArr = paramsArr;
      this.columnsTitleArr = titleArr;
      this.printColumnsArr = colArr;
      // console.log(colArr,titleArr,paramsArr)
    },
    handleTableChange (pagination, filters) {
      ['styleNo', 'styleName', 'moNo', 'bedNo', 'lot'].forEach(i => {
        this.queryParam[i] = (filters || {})[i]
      })
      this.ipagination = Object.assign(this.ipagination, pagination)
      this.loadData()
    },
    initColoum () {
      // 款号  款名  制单号 床号
      let columnsList = cloneDeep(this.columns)
      columnsList.forEach(i => {
        // if (['styleNo', 'styleName', 'moNo'].includes(i.dataIndex)) {
        //   i.slots = { filterDropdown: 'filterDropdown', customRender: 'customRender' }
        // }
        if (i.dataIndex == 'styleNo') {
          i.filters = this.styleList.map(el => ({ text: el.styleNo, value: el.styleNo }))
        }
        if (i.dataIndex == 'styleName') {
          i.filters = this.styleList.map(el => ({ text: el.name, value: el.name }))
        }
        if (i.dataIndex == 'moNo') {
          i.filters = this.allMakeList.map(el => ({ text: el.moNo, value: el.moNo }))
        }
        if (i.dataIndex == 'lot') {
          i.filters = this.lotList.map(el => ({ text: el, value: el }))
        }
      })
      this.columns = columnsList
    },
    async getLotList () {
      let res = await axios.postAction('/api/mo/mo/get-lot-list')
      if (res.success) this.lotList = res.data
    }
  },
  async created () {
    await store.dispatch('getStyle')
    await store.dispatch('getAllMake')
    await this.getLotList()
    this.initColoum()
  }
}
</script>
